#include "ClientNet.h"
#include <iostream>
#include <string>
using namespace std;

int ClientNet::Connect(int port, const char* address)
{
	// 用于记录错误信息并输出
	int errMsg;

	// 启动WinSock
	WSAData wsaData;
	errMsg = WSAStartup(MAKEWORD(1, 1), &wsaData);

	if(errMsg != NO_ERROR)
	{
		printf("Failed with wsaStartup ,error : %d\n", errMsg);
		return 1;
	}

	// 创建 socket
	m_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(m_sock == INVALID_SOCKET)
	{
		printf("socket falied with error: %d\n", WSAGetLastError());
		return 2;
	}

	// 目标服务器数据
	sockaddr_in sockaddrServer;
	sockaddrServer.sin_family = AF_INET;
	sockaddrServer.sin_port = port;
	sockaddrServer.sin_addr.s_addr = inet_addr(address);

	// 链接，sock 与目标服务器链接
	errMsg = connect(m_sock, (sockaddr*)&sockaddrServer, sizeof(sockaddrServer));
	if(errMsg < 0)
	{
		printf("connect falied with error : %d\n", errMsg);
		return 3;
	}


}

int ClientNet::sendMsg(const char* msg, int len)
{
	int errMsg = 0;

	// 给指定 sock 发送消息
	errMsg = send(m_sock, msg, len, 0);
	if(errMsg < 0)
	{
		printf("send falied with error : %d\n", errMsg);
		return 1;
	}
	return 0;
}

void ClientNet::Close()
{
	closesocket(m_sock);
}


int main()
{
	ClientNet client;

	char* message;

	// 连接到本地服务器，端口号为 8888
	printf("connect to \n");
	client.Connect(8888, "127.0.0.1");

	int go = 1;
	string go_str = "yes";
	
	// 发送消息
	do{
		printf("Input you message \n");
		cin>>message;
		// message = strcat((char*)"Hello world", "\0");
		client.sendMsg(message, sizeof(message));
		printf("Continue to send message ? yes/no \n");
		cin>>go_str;
		if(go_str != "yes"){
			go = 0;
		}
	}while(go);
	

	//关闭socket
	printf("close socket\n");
	client.Close();

	system("pause");

	return 0;
}